<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of vote
 *
 * @author b4by
 */
class vote extends MY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('model_image');
	}

	public function up($id = '') {
		if (!is_numeric($id))
			$id = 0;

		$image = $this->model_image->get_info($id);
		$json = array(
			'state' => 'error',
			'message' => lang('error'),
		);
		$voted = $this->session->userdata['voted'];
		if ($image && $image->active == 0) {
			if (!isset($voted[$id]) || (isset($voted[$id]) && $voted[$id] === FALSE)) {
				$image->vote_up++;
				if (isset($voted[$id]) && $voted[$id] === FALSE)
					$image->vote_down = $image->vote_down - 1;
				$this->model_image->update($id, array(
					'active' => ($image->vote_up - $image->vote_down) >= $this->siteConfig->vote_pass ? 1 : 0,
					'vote_up' => $image->vote_up,
					'vote_down' => $image->vote_down,
				));
				$voted[$id] = TRUE;
				$this->session->set_userdata('voted', $voted);
				$json = array(
					'state' => 'success',
					'message' => lang('vote_success'),
				);
			} else {
				$json = array(
					'state' => 'error',
					'message' => lang('image_voted')
				);
			}
		}

		echo json_encode($json);
	}

	public function down($id = '') {
		if (!is_numeric($id))
			$id = 0;

		$image = $this->model_image->get_info($id);
		$json = array(
			'state' => 'error',
			'message' => lang('error'),
		);
		$voted = $this->session->userdata['voted'];
		if ($image && $image->active == 0) {
			if (!isset($voted[$id]) || (isset($voted[$id]) && $voted[$id] === TRUE)) {
				$image->vote_down++;
				if ($voted[$id] === TRUE)
					$image->vote_up = $image->vote_up - 1;
				$this->model_image->update($id, array(
					'active' => ($image->vote_up - $image->vote_down) >= $this->siteConfig->vote_pass ? 1 : 0,
					'vote_down' => $image->vote_down,
					'vote_up' => $image->vote_up,
				));
				$voted[$id] = FALSE;
				$this->session->set_userdata('voted', $voted);
				$json = array(
					'state' => 'success',
					'message' => lang('vote_success'),
				);
			}
			else {
				$json = array(
					'state' => 'error',
					'message' => lang('image_voted')
				);
			}
		}

		echo json_encode($json);
	}

}

?>
